﻿Imports System.Threading

Namespace GameState
  Public Class WaitAndProcessSecondTurnGameState
    Inherits AbstractGameState

    Private Const WAIT_TIME As Integer = 3000 'three seconds

    Friend Overrides Sub OnActivate()
      'follow-up after a few seconds
      Dim thread As New Thread(AddressOf Process)
      thread.Start()
    End Sub

    ''' <summary>
    ''' process second turn outcome
    ''' </summary>
    ''' <param name="state">Nothing</param>
    Public Sub Process(ByVal state As Object)

      'wait some time, so user can see his/her selection of cards
      Thread.Sleep(WAIT_TIME)

      Dim player As Player = MovingPlayer()
      If player Is Nothing Then
        Throw New InvalidOperationException("Player not found after wait")
      End If

      'process results
      If player.TurnState = player.TurnStateE.WinsTurn Then

        'gains the cards
        player.AddCardsetAfterWin(FirstCard, SecondCard)

        'remove from the board
        FirstCard.TakeFromBoard()
        SecondCard.TakeFromBoard()

        'player gets another move
        player.SetTurnState(player.TurnStateE.MayMakeFirstMove)
      Else
        'player lost move
        player.SetTurnState(player.TurnStateE.Inactive)

        'find next player and set it to make the first move
        Dim nextPlayer As Player = Me.NextPlayer(player)
        nextPlayer.SetTurnState(player.TurnStateE.MayMakeFirstMove)
      End If

      'restore cards
      flipCardsBack()

      'check if there are any cards left
      'set next state: 
      If cardsLeft() = 0 Then
        'no cards left, finish game
        adviceGameState(Of FinishedGameState)()
      Else
        'first move again for the next (or same) player
        adviceGameState(Of FirstMoveGameState)()
      End If

    End Sub

    Private Sub flipCardsBack()
      'turn both cards back
      FirstCard.Turn()
      SecondCard.Turn()

      FirstCard = Nothing
      SecondCard = Nothing
    End Sub

    ''' <summary>
    ''' how many cards still in the game
    ''' </summary>
    Private Function cardsLeft() As Integer
      Dim count = 0
      For Each card In CardsList
        If Not card.Taken Then
          count += 1
        End If
      Next
      Return count
    End Function

  End Class
End Namespace